﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace EasyCore.UnifyResult
{
    public class EasyAdminResultProvider
    {  
        public static RESTfulApiResult OnResponsedResult(HttpContext context,int statusCode) {
            switch (statusCode)
            {
  
                case StatusCodes.Status401Unauthorized:               // 处理 401 状态码
                    return new RESTfulApiResult(statusCode, errors: "登录已过期，请重新登录");
                    break;     
                case StatusCodes.Status403Forbidden:            // 处理 403 状态码
                    return new RESTfulApiResult(statusCode, errors: "禁止访问，没有权限", data: context.Request.Path);   
                default: 
                    break;
            }
            return null;
        }

        /// <summary>
        /// 跳过规范化处理的 Response Content-Type
        /// </summary>
        internal static string[] ResponseContentTypesOfNonUnify = new[]
        {
        "text/event-stream",
        "application/pdf",
        "application/octet-stream",
        "image/"
    };

        internal static bool CheckHttpContextNonUnify(HttpContext httpContext)
        {
            var contentType = httpContext.Response.Headers["content-type"].ToString();
            if (ResponseContentTypesOfNonUnify.Any(u => contentType.Contains(u, StringComparison.OrdinalIgnoreCase)))
            {
                return true;
            }

            return false;
        }


        internal static bool CheckVaildResult(IActionResult result, out object data)
        {
            data = default;

            // 排除以下结果，跳过规范化处理
            var isDataResult = result switch
            {
                ViewResult => false,
                PartialViewResult => false,
                FileResult => false,
                ChallengeResult => false,
                SignInResult => false,
                SignOutResult => false,
                RedirectToPageResult => false,
                RedirectToRouteResult => false,
                RedirectResult => false,
                RedirectToActionResult => false,
                LocalRedirectResult => false,
                ForbidResult => false,
                ViewComponentResult => false,
                PageResult => false,
                NotFoundResult => false,
                NotFoundObjectResult => false,
                _ => true,
            };

            // 目前支持返回值 ActionResult
            if (isDataResult) data = result switch
            {
                // 处理内容结果
                ContentResult content => content.Content,
                // 处理对象结果
                ObjectResult obj => obj.Value,
                // 处理 JSON 对象
                JsonResult json => json.Value,
                _ => null,
            };

            return isDataResult;
        }



    }
}
